package com.oocl.jms.listenrer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.log4j.Logger;

import com.oocl.jms.parser.MessageParser;
import com.oocl.jms.parser.impl.MessageParserImpl;
import com.oocl.pojo.Merchant;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;

public class MerchantMessageListener implements MessageListener {
	Logger logger = Logger.getLogger(MerchantMessageListener.class);
	private MessageParser parser;
	private MerchantManager manager;
	
	public MerchantMessageListener() {
		parser = new MessageParserImpl();
		manager = MerchantManagerFactory.getInstance();
	}

	@Override
	public void onMessage(Message message) {
		try {
			logger.info("MerchantMessageListener receive a message "+message.getJMSMessageID());
			Merchant merchant = parser.parser(message);
			Merchant m1 = manager.findMerchantById(merchant.getId());
			if(null==m1){
				manager.add(merchant);
			}else {
				manager.update(merchant);
			}
			message.acknowledge();
			logger.info("MerchantMessageListener acknowledge the message "+message.getJMSMessageID());
		} catch (JMSException e) {
			logger.error("MerchantMessageListener pasing message appear exeception  "+e.getMessage());
		}
	}

}
